import OSS from 'ali-oss';
import stream from 'stream';
import { v4 as uuidv4 } from 'uuid';
import BaseController from '../../core/baseController';
import { getCurrentStimp } from '../../utils/index';

const Duplex = stream.Duplex;

export default class NavController extends BaseController {
  constructor(ctx) {
    super(ctx)
    this.service = ctx.service.shop.qr,
    this.modelPrefix = 'merchant.qr';
    const { oss } = this.ctx.app.config;
    this.ctx.client = new OSS(oss);
  }


  async create() {
    const { body } = this.ctx.validateReq(`${this.modelPrefix}.create`);
    const { table_number } = body;

    const stemp = getCurrentStimp();
    Object.assign(body, {
      create_at: stemp,
      update_at: stemp,
    });

    const access_token = await this.service.getAccessToken();

    let qrcodeurl = `https://api.weixin.qq.com/wxa/getwxacode?access_token=${access_token}`;

    const ans = await this.ctx.curl(qrcodeurl, {
      method: 'POST',
      contentType: 'json',
      data: {
        // 'scene': `TB_${table_number}`,
        'path': 'pages/goods/entry/index?tb='+ table_number,
        'width': 350,
        'is_hyaline': false
      }
    });

    const base64Img = ans.data.toString('base64');

    const dataBuffer = new Buffer(base64Img, 'base64');
    const Stream: any = new Duplex();
    Stream.push(dataBuffer);
    Stream.push(null);
    // 上传图片到OSS或者COS
    const filename = `public/${uuidv4()}.png`;
    const { url } = await this.ctx.client.put(filename, Stream);

    Object.assign(body, { url });
    await this.service.create(body);

    this.ctx.success({
      data: {
        url,
        filename: Stream.filename
      },
      status: 201,
    });

  }

}
